package com.ycl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycl.common.Result;
import com.ycl.dto.SetmealDto;
import com.ycl.entity.Category;
import com.ycl.entity.Dish;
import com.ycl.entity.Setmeal;
import com.ycl.entity.SetmealDish;
import com.ycl.service.CategoryService;
import com.ycl.service.DishService;
import com.ycl.service.SetmealDishService;
import com.ycl.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    SetmealService setmealService;
    @Autowired
    SetmealDishService setmealDishService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishService dishService;
    //@Autowired
    //CacheManager cacheManager;// CacheManage : 缓存接口，里面封存所有缓存数据

    /**
     * 新增套餐
     * CachePut:将方法返回值放入缓存
     * value: 缓存的名称，每个缓存下可以有多个key
     * key: 缓存的key （#p0.id）(#result.id)(#root.args[0].id)(#setmeal.id)
     * @param setmealDto
     * @return
     */
    @Caching(evict = {
            @CacheEvict(value = "setmealCache",key = "#setmealDto.categoryId+'_1'")
    })
    @CachePut(value = "setmealCache",key = "#setmealDto.id")
    //@CachePut(value = "setmealCache",key = "#p0.id")
    //@CachePut(value = "setmealCache",key = "#root.args[0].id")
    //@CachePut(value = "setmealCache",key = "#result.id")
    @PostMapping
    public Result<String> save(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());

        setmealService.saveWithDish(setmealDto);
        return Result.success("新增套餐成功");
    }

    // 缓存页面信息后，当增删改都要清楚页面缓存不方便
    //@Cacheable(value = "setmealCache",key = "'setmeal_page'+#page+'_pageSize'+#pageSize",unless = "#result.data == null ")
    @GetMapping("/page")
    public Result<Page<SetmealDto>> get(int page,int pageSize,String name){
        // 分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件，根据name进行模糊查询
        queryWrapper.like(name != null,Setmeal::getName,name);
        // 添加排序条件，根据更新时间降序排序
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);
        // 拷贝对象
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();


        List<SetmealDto> list = records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            // 拷贝对象
            BeanUtils.copyProperties(item,setmealDto);
            // 分类ID
            Long categoryId = item.getCategoryId();
            // 根据分类ID查询分类对象
            Category category = categoryService.getById(categoryId);
            // 分类名称
            String categoryName = category.getName();

            setmealDto.setCategoryName(categoryName);
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);

        return Result.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true) // allEntries: 删除该缓存下所有的数据
    @DeleteMapping
    public Result<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);
        setmealService.deleteWithDish(ids);
        return Result.success("删除成功");
    }


    @Caching(evict = {
            @CacheEvict(value = "setmealCache",key = "#result.data[0].categoryId + '_1'" ),
            @CacheEvict(value = "setmealCache",key = "#ids")
    })
    @PostMapping("/status/{status}")
    public Result<List<Setmeal>> status(@PathVariable int status,@RequestParam List<Long> ids){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null,Setmeal::getId,ids);
        List<Setmeal> list = setmealService.list(queryWrapper).stream().map((item)->{
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());

        setmealService.updateBatchById(list);
        return Result.success(list);
    }

    @Cacheable(value = "setmealCache",key = "#id" ,unless = "#result == null")
    @GetMapping("/{id}")
    public Result<SetmealDto> get(@PathVariable Long id){
        log.info("id：{}",id);
        SetmealDto setmealDto = setmealService.getWithDish(id);
        return Result.success(setmealDto);
    }

    /**
     *
     * @param setmealDto
     * @return
     */
    @Caching(evict = {
            @CacheEvict(value = "setmealCache",key = "#setmealDto.categoryId + '_' +#setmealDto.status" ),
            @CacheEvict(value = "setmealCache",key = "#setmealDto.id")
    })

    @PutMapping
    public Result<String> update(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());
        log.info(setmealDto.getStatus().toString());
        setmealService.updateWithDish(setmealDto);
        return Result.success("修改成功");
    }


    /**
     * 根据套餐分类查询套餐(返回SetmealDto)
     * @param setmeal
     * @return
     */
    /**
     * 根据套餐分类查询套餐(返回Setmeal)
     * @Cacheable： 在执行方法前spring先查看缓存中是否有数据，如果有直接返回缓存数据，没有则访问数据库，并存入缓存
     * condition-满足条件才存入缓存  unless-满足条件就不存入缓存
     * value: 缓存的名称，每个缓存下可以有多个key
     * key: 缓存的key （#p0.id）(#result.id)(#root.args[0].id)(#setmeal.id)
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' +#setmeal.status")
    public Result<List<Setmeal>> list(Setmeal setmeal){
        // 获取套餐setmeal信息
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(setmeal != null,Setmeal::getStatus,1)
                .eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(queryWrapper);

        return Result.success(list);
    }
/*    @GetMapping("/list")
    public Result<List<SetmealDto>> list(SetmealDto setmeal){
        // 获取套餐setmeal信息
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(setmeal != null,Setmeal::getStatus,1)
                .eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId())
                .orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> list = setmealService.list(queryWrapper);

        // TODO 获取setmealDto信息
        String categoryName = categoryService.getById(setmeal.getCategoryId()).getName();
        List<SetmealDto> setmealDtoList = list.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            setmealDto.setCategoryName(categoryName);
            LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,item.getId());
            List<SetmealDish> setmealDishList = setmealDishService.list(dishLambdaQueryWrapper);
            setmealDto.setSetmealDishes(setmealDishList);
            return setmealDto;
        }).collect(Collectors.toList());
        return Result.success(setmealDtoList);
    }*/

    /**
     * 根据套餐ID获取套餐里菜品信息
     * @param id
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#id",unless = "#result.data == null")
    @GetMapping("/dish/{id}")
    public Result<List<Dish>> getDish(@PathVariable Long id){
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        List<Dish> dishList = list.stream().map((item)->{
            Dish dish = dishService.getById(item.getDishId());
            return dish;
        }).collect(Collectors.toList());
        return Result.success(dishList);
    }
}
// 13333333333
